/**
 *
 * @param element 收藏元素
 * @param url 收藏url
 * @param collectKey 收藏主键
 * @param event 移动端收藏事件
 */
function collectAction({element, url, collectKey, event}) {
    element.showLoading()
    const popoverEle = element.parentElement
    if (element.classList.contains('is-collect')) {
        _axios.delete(url, {
            data: {
                collectId: element.getAttribute('data-fid')
            }
        }).then(res => {
            if (res.Code !== 200) {
                console.error(res)
            } else {
                element.classList.remove('is-collect')
                element.querySelector('.iconfont').className = 'iconfont iconshoucang'
                if (!gugeeGobal.isMobile) {
                    popoverEle.setAttribute('content', 'Add to Favorite')
                    initPopover(popoverEle)
                }
            }
            element.hideLoading()
        })
    } else {
        const params = {}
        params[collectKey] = element.getAttribute('data-id')
        _axios.post(url, params).then(res => {
            if (res.Code === 200) {
                element.classList.add('is-collect')
                element.querySelector('.iconfont').className = 'iconfont iconquxiaoshoucang33'
                element.setAttribute('data-fid', res.Data.collectId)
                if (!gugeeGobal.isMobile) {
                    popoverEle.setAttribute('content', 'Remove from Favorite')
                    initPopover(popoverEle)
                }
            }
            element.hideLoading()
        })
    }

    //移动端阻止默认事件
    if(gugeeGobal.isMobile) {
        event && (event.preventDefault() || event.stopPropagation())
    }
}

function getGridList(config) {
    /**
     * @param loadingElement loading元素
     * @param url 请求url
     * @param params url参数
     * @param listWrap 主要内容
     * @param footerElement 尾部元素
     * @param listDomFunc 内容填充方法
     * @param otherEvent 其他事件
     */
    const {loadingElement, url, params, listWrap = loadingElement, footerElement, listDomFunc, requestType = 'GET', otherEvent} = config
    loadingElement.showLoading()
    let axiosReq
    if(requestType === 'GET') {
        const requestUrl = getEncodeUrl(url, params)
        axiosReq = _axios.get(requestUrl)
    } else if(requestType === 'POST') {
        axiosReq = _axios.post(url, params)
    }
    axiosReq.then(res => {
        if (res.Code === 200) {
            if (res.Data.totalRow === 0) {
                showNoDataImg(listWrap)
                footerElement && footerElement.hide()
            } else {
                if (res.Data.lastPage) {
                    footerElement && footerElement.hide()
                } else {
                    footerElement && footerElement.show()
                }
                let str = ''
                if (!res.Data.firstPage) {
                    str = listWrap.innerHTML
                }
                res.Data.list.forEach(item => {
                    str += listDomFunc(item)
                })
                listWrap.innerHTML = str

                // 其他事件
                otherEvent && otherEvent()
            }
        }
        loadingElement.hideLoading()
    })
}

function troggleActive(element, afterEvent) {
    if (!element.classList.contains('is-active')) {
        const parent = element.parentElement
        parent.querySelector('.is-active').classList.remove('is-active')
        element.classList.add('is-active')

        afterEvent && afterEvent()
    }
}

function openDetail(id,shortcode) {
    if(!gugeeGobal.isLogin) {
        toLogin()
        return false
    }
    showLoading()
    _axios.get('/ins/media/' + id).then(res => {
        hideLoading()
        if (res.Code === 200) {
            const item = res.Data
            // detail-top
            let wrap = '<div class="detail-top">' +
                '<div class="ad-info">' +
                '<div class="cover">' +
                '<img width="100" height="100" src="' + getImage(item.displayUrl,IMAGE_TYPE.MEDIA,IMAGE_SIZE.SMALL) + '" alt="display image">'
            if (item.isVideo) {
                wrap += '<i class="iconfont iconinsvideo-16px"></i>'
            } else {
                wrap += '<i class="iconfont iconMultiPhoto-16px"></i>'
            }
            if (item.isSponsored) {
                wrap += '<div class="post-detail-mask">' +
                    'Sponsored' +
                    '</div>'
            }
            wrap += '</div>' +
                '<div class="ad-caption">'
            if (gugeeGobal.isMobile){
                wrap += '<div class="title-top">' +
                    '<div class="title">' + item.caption + '</div>'
                if(item.collectId) {
                    wrap += '<div class="gd-popover" content="Remove from Favorite">' +
                        '<div class="icon-collect is-collect" data-fid="' + item.collectId + '" data-id="' + item.id + '">' +
                        '<i class="iconfont iconquxiaoshoucang33"></i>' +
                        '</div>' +
                        '</div>' +
                        '</div>'
                } else {
                    wrap += '<div class="gd-popover" content="Add to Favorite">' +
                        '<div class="icon-collect" data-id="' + item.id + '">' +
                        '<i class="iconfont iconshoucang"></i>' +
                        '</div>' +
                        '</div>' +
                        '</div>'
                }
            }else {
                wrap += '<div class="title">' + item.caption + '</div>'
            }
            wrap += '<div class="sub-title">Posted on ' + formatTime(+item.takenTime, 'MM-DD-YYYY HH:mm:ss') +' UTC '
            if (item.score >= 90) {
                wrap += '<span class="gd-score red">'
            } else if (item.score < 90 && item.score >= 80) {
                wrap += '<span class="gd-score orange">'
            } else if (item.score < 80 && item.score >= 70) {
                wrap += '<span class="gd-score green">'
            } else {
                wrap += '<span class="gd-score gray">'
            }
            wrap  += '<i class="iconfont iconhuo"></i>' + numFormat(+item.score) +
                '</span>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="ad-action">' +
                '<a target="_blank" href="https://www.instagram.com/p/' + item.shortcode + '">' +
                '<button class="gd-btn btn-info">View Post</button>' +
                '</a>' +
                '</div>'
            if (!gugeeGobal.isMobile){
                if(item.collectId) {
                    wrap += '<div class="gd-popover" content="Remove from Favorite">' +
                        '<div class="icon-collect is-collect" data-fid="' + item.collectId + '" data-id="' + item.id + '">' +
                        '<i class="iconfont iconquxiaoshoucang33"></i>' +
                        '</div>' +
                        '</div>'
                } else {
                    wrap += '<div class="gd-popover" content="Add to Favorite">' +
                        '<div class="icon-collect" data-id="' + item.id + '">' +
                        '<i class="iconfont iconshoucang"></i>' +
                        '</div>' +
                        '</div>'
                }
            }
            wrap += '</div>'

            const bloggerInfo = item.insBloggerInfo
            wrap += '<div class="ad-data">' +
                '<div class="ad-blogger-info">' +
                '<a href="/instagram/influencer/' + bloggerInfo.username + '" target="_blank">' +
                '<div class="avatar">' +
                '<img class="icon" src="' + getImage(bloggerInfo.picUrl,IMAGE_TYPE.BLOGGER,IMAGE_SIZE.SMALL) + '" alt="blogger avatar"/>'
            if (bloggerInfo.isVerified) {
                wrap += '<img class="auth" src="/static/img/ins/Authentication.png" srcset="/static/img/ins/Authentication@2x.png 2x" alt="auth">'
            }
            wrap += '</div>' +
                '</a>' +
                '<div class="blogger-info">' +
                '<div class="title">' + bloggerInfo.username + '</div>' +
                '<div class="sub-title">' + bloggerInfo.fullName + '</div>' +
                '</div>' +
                '</div>' +
                '<div class="blogger-data">' +
                '<div class="blogger-data-item">' +
                '<div class="title">Followers</div>' +
                '<div class="sub-title">' + numFormat(bloggerInfo.followerCount) + '</div>' +
                '</div>' +
                '<div class="blogger-data-item mobile-hide">' +
                '<div class="title">Avg Views</div>' +
                '<div class="sub-title">' + numFormat(bloggerInfo.avgViews) + '</div>' +
                '</div>' +
                '<div class="blogger-data-item mobile-hide">' +
                '<div class="title">Avg Likes</div>' +
                '<div class="sub-title">' + numFormat(bloggerInfo.avgLikes) + '</div>' +
                '</div>' +
                '<div class="blogger-data-item mobile-hide">' +
                '<div class="title">Avg Reviews</div>' +
                '<div class="sub-title">' + numFormat(bloggerInfo.avgReviews) + '</div>' +
                '</div>' +
                '<div class="blogger-data-item">' +
                '<div class="title">Avg ER</div>' +
                '<div class="sub-title">' + numFormat(bloggerInfo.avgEr * 100) + '%</div>' +
                '</div>' +
                '</div>' +
                '</div>'

            wrap += '<div class="post-figure">' +
                '<div class="main-title">Post Figures</div>' +
                '<div class="post-figure-list">' +
                '<div class="post-figure-item">' +
                '<div class="title">Views</div>'
            if (item.isVideo) {
                wrap += '<div class="sub-title">' + (item.videoViewCount ? numFormat(item.videoViewCount) : '-') + '</div>'
            } else {
                wrap += '<div class="sub-title"> - </div>'
            }
            wrap += '</div>' +
                '<div class="post-figure-item">' +
                '<div class="title">Likes</div>' +
                '<div class="sub-title">' + numFormat(item.likeCount) + '</div>' +
                '</div>' +
                '<div class="post-figure-item">' +
                '<div class="title">Reviews</div>' +
                '<div class="sub-title">' + numFormat(item.commentCount) + '</div>' +
                '</div>' +
                '<div class="post-figure-item">' +
                '<div class="title">ER</div>' +
                '<div class="sub-title">' + numFormat(item.er * 100) + '%</div>' +
                '</div>' +
                '</div>' +
                '</div>'

            wrap += '<div class="post-per">' +
                '<div class="main-title">Post Performance</div>' +
                '<div class="chart-con" id="postPerChart"></div>' +
                '</div>'

            const taggedBloggers = item.taggedBloggers
            wrap += '<div class="tag-account">' +
                '<div class="main-title">Tagged Accounts</div>'
            if(taggedBloggers && (taggedBloggers.length > 0)) {
                wrap += '<div class="account-wrap">' +
                    '<div class="tag-list">'
                taggedBloggers.forEach(tag => {
                    wrap += '<div class="tag-item">' +
                        '<div class="avatar"><img width="48" height="48" src="' + getImage(tag.picUrl,IMAGE_TYPE.BLOGGER,IMAGE_SIZE.SMALL) + '" alt="image"/></div>' +
                        '<div class="tag-info">' +
                        '<div class="title">' + tag.username + '</div>' +
                        '<div class="sub-title">' + (tag.fullName || '') + '</div>' +
                        '</div>' +
                        '</div>'
                })
                wrap += '</div>'
            } else {
                wrap += '<div class="account-wrap" style="min-height: 220px">' +
                    '<div class="no-data">' +
                    '<img width="131" height="131" src="/static/img/ins/noData.png" alt="no data img" srcset="/static/img/ins/noData@2x.png 2x, /static/img/ins/noData@3x.png 3x">' +
                    '<div class="title">No related data available</div>' +
                    '</div>'
            }
            wrap += '</div>' +
                '</div>' +
                '<div class="tag-product">' +
                '<div class="main-title">Tagged Product</div>' +
                '<div class="product-wrap">' +
                '<div class="grid-list">' +
                '<div class="grid-list__inner row-3"></div>' +
                '<div class="grid-list__footer" style="display: none">' +
                '<span>View More</span>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>'
            showModal({
                class: 'post-detail-modal',
                title: 'Post Detail',
                content: wrap,
                position: {
                    top: 100
                },
                isShowConfirmBtn: false,
                isShowCancelBtn: false,
                afterShowEvent: () => {
                    const chart = echarts.init(document.getElementById('postPerChart'))
                    const postPerformance = item.postPerformance
                    const levelPostPerformance = item.levelPostPerformance
                    const option = {
                        color: ['#8267F1', '#1FDBBE'],
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            },
                            formatter: (params) => {
                                let str = params[0].axisValue + '<br>' +
                                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#8267F1;"></span>' +
                                    'of the post ' + numFormat(+params[0].data) + '%' + '<br>' +
                                    '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#1FDBBE;"></span>' +
                                    'of similar accounts (the average) ' + numFormat(+params[1].data) + '%'
                                return str
                            }
                        },
                        legend: {
                            data: ['Figures of the post', 'Avg figures of similar account'],
                        },
                        grid: {
                            top: 24,
                            left: '3%',

                            containLabel: true
                        },
                        xAxis: {
                            type: 'value',
                            axisTick: {
                                show: false//不显示坐标轴刻度线
                            },
                            axisLine: {
                                show: false,//不显示坐标轴线
                            },
                            axisLabel: {
                                formatter: '{value}%',
                                textStyle: {
                                    color: '#909399'   //坐标轴字体颜色
                                }
                            },
                            boundaryGap: [0, 0.01]
                        },
                        yAxis: {
                            type: 'category',
                            axisLine: {
                                lineStyle: {
                                    color: '#909399'
                                },
                                textStyle: {
                                    color: '#909399'   //坐标轴字体颜色
                                }
                            },
                            axisLabel: {
                                textStyle: {
                                    color: '#909399'   //坐标轴字体颜色
                                }
                            },
                            data: ['ER', 'Review Rate', 'Like Rate', 'View Rate']
                        },
                        series: [
                            {
                                name: 'Figures of the post',
                                type: 'bar',
                                barWidth: 10,
                                itemStyle: {
                                    normal: {
                                        //柱形图圆角，初始化效果
                                        barBorderRadius: [0, 5, 5, 0]
                                    }
                                },
                                data: [
                                    (postPerformance.er * 100).toFixed(1),
                                    (postPerformance.reviewRate * 100).toFixed(1),
                                    (postPerformance.likeRate * 100).toFixed(1),
                                    (postPerformance.viewRate * 100).toFixed(1),
                                ]
                            },
                            {
                                name: 'Avg figures of similar account',
                                type: 'bar',
                                barWidth: 10,
                                itemStyle: {
                                    normal: {
                                        //柱形图圆角，初始化效果
                                        barBorderRadius: [0, 5, 5, 0]
                                    }
                                },
                                data: levelPostPerformance ? [
                                    (levelPostPerformance.er * 100).toFixed(1),
                                    (levelPostPerformance.reviewRate * 100).toFixed(1),
                                    (levelPostPerformance.likeRate * 100).toFixed(1),
                                    (levelPostPerformance.viewRate * 100).toFixed(1),
                                ] : [0, 0, 0, 0]
                            }
                        ]
                    }
                    if(gugeeGobal.isMobile) {
                        option.tooltip.position = [ 24, '30%']
                        option.legend.bottom = 16
                        option.grid.bottom = 72
                        option.grid.right = 24
                    } else {
                        option.legend.bottom = 24
                        option.grid.bottom = 64
                        option.grid.right = '4%'
                    }

                    if (!item.isVideo) {
                        option.yAxis.data.pop()
                        option.series[0].data.pop()
                        option.series[1].data.pop()
                    }
                    chart.setOption(option)
                }
            })
            const tagProduct = document.querySelector('.product-wrap')
            adTagProduct(shortcode,tagProduct)

            document.querySelector('.post-detail-modal .icon-collect').addEventListener('click',() => {
                collectAction({
                    element: document.querySelector('.post-detail-modal .icon-collect'),
                    url: '/ins/fa/media',
                    collectKey: 'mid'
                })
            })
            if (gugeeOS.isIPhone) {
                document.querySelector('.post-detail-modal .modal-body .tag-product').style.marginBottom = '160px'
            }
        }
    })
}
function adTagProduct (id,wrap) {
    const footer = document.querySelector('.product-wrap .grid-list__footer')
    const params = {
        page: 1,
        pageSize: 6,
    }
    const getGridListParams = {
        loadingElement: wrap.querySelector('.grid-list'),
        url: '/ins/product/list/'+ id,
        params,
        listWrap: wrap.querySelector('.grid-list__inner'),
        footerElement: footer,
        listDomFunc: item => {
            let str = ''
            str +='<a href="/instagram/product/' + item.productId + '">' +
                '<div class="grid-item">' +
                '<div class="avatar">' +
                '<img  width="80" height="80" src="' + getImage(item.image,IMAGE_TYPE.PRODUCT,IMAGE_SIZE.SMALL)+ '" alt="image"></div>' +
                '<div class="tag-info">' +
                '<div class="title">' + item.productName + '</div>' +
                '<div class="sub-title">' + item.price + '</div>' +
                '<div class="title-bottom">' +
                '<img width="20" height="20" src="' + getImage(item.picUrl,IMAGE_TYPE.BLOGGER,IMAGE_SIZE.SMALL) + '" alt="image">' +
                '<div class="bottom-title">' + item.username + '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</a>'
            return str
        }
    }
    footer.querySelector('span').addEventListener('click', () => {
        params.page ++
        getGridList(getGridListParams)
    })

    getGridList(getGridListParams)
}

export {
    collectAction,
    getGridList,
    troggleActive,
    openDetail
}